package my.diplom.util;

import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.context.SecurityContextHolder;

/**
 * Created by IntelliJ IDEA.
 * User: gb
 * Date: 20.08.2009
 * Time: 2:08:42
 * To change this template use File | Settings | File Templates.
 */
public class UserUtil {

    public static String getRemoteUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || auth.getPrincipal() == null)
            return null;
        if (auth.getPrincipal() instanceof UserDetails)
            return ((UserDetails) auth.getPrincipal()).getUsername();
        else
            return auth.getPrincipal().toString();
    }

   public static boolean  isAdmin() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            GrantedAuthority[] authority = authentication.getAuthorities();
            boolean isAdmin = false;
            for (int i = 0; i < authority.length; i++) {
                if (authority[i].equals("ROLE_ADMIN")) {
                    isAdmin = true;
                    break;
                }
            }
            if (isAdmin) {
                return true;
            } else {
                return false;

            }
        }

        return false;
    }
}
